import { Byte } from '../../api/io/Byte';
import { HashMap } from '../../api/struct/HashMap';
import { Shop } from './Shop';
import { ShopSell } from './ShopSell';
import { ITimer } from '../../api/timer/ITimer';
import { IAsync } from '../../api/event/IAsync';
import { MathUtils } from '../../api/math/MathUtils';



/**商店属性枚举*/
export const enum E_ShopManager {
	/**各个商店*/
	SHOP = 0,
	/**已销售数量*/
	SELL = 1,
	/**枚举数量*/
	EnumCount = 2
}


/**商店*/
export class ShopManager {
	/**事件ID*/
	public static readonly EVENT_ID = 'STRUCT_DATA_SHOP_MANAGER_EVENT_ID';
	/**整体更新事件ID（部分只需要监听整体变化）*/
	public static readonly TOTAL_EVENT_ID = 'STRUCT_DATA_SHOP_MANAGER_TOTAL_EVENT_ID';
	/**缓存池*/
	private static POOL: ShopManager[] = [];

	/**创建入口*/
	public static create(json?: string): ShopManager {
		const c = this.POOL.pop() || new ShopManager();
		c._destroyed = false;
		c.resetProperty();
		if (json) {
			c.parse(json);
		}
		return c;
	}


	/**已释放*/
	protected _destroyed = false;
	/**各个商店*/
	protected _shop: HashMap<number, Shop> = null;
	/**已销售数量*/
	protected _sell: HashMap<number, ShopSell> = null;


	/**构建函数-私有，防止外部创建*/
	private constructor() {
	}


	/**释放*/
	public destroy(): void {
		if (this._destroyed) {
			return;
		}
		this._destroyed = true;
		this.resetProperty(true);
		if (ShopManager.POOL.indexOf(this) === -1) {
			ShopManager.POOL.push(this);
		}
	}

	/**设置各个商店*/
	public putShop(k: number, v: Shop): Shop {
		const ov = this._shop.put(k, v);
		return ov;
	}


	/**获取各个商店*/
	public getShop(k: number) {
		return this._shop.get(k);
	}


	/**删除各个商店*/
	public removeShop(k: number, autoDestroy = false): Shop {
		const ov = this._shop.remove(k);
		if (autoDestroy && ov) {
			ov.destroy();
		}
		return ov;
	}


	/**获取各个商店映射表-键值(外部改变将导致出错，只能用于遍历)*/
	public getShopKeys(): number[] {
		return this._shop.getKeys();
	}


	/**获取各个商店映射表-值(外部改变将导致出错，只能用于遍历)*/
	public getShopValues(): Shop[] {
		return this._shop.getValues();
	}


	/**清空各个商店映射表*/
	public clearShopMap(autoDestroy = false): void {
		const ks = this._shop.getKeys();
		for (let i = ks.length - 1; i >= 0; i--) {
			this.removeShop(ks[i], autoDestroy);
		}
	}


	/**设置已销售数量*/
	public putSell(k: number, v: ShopSell): ShopSell {
		const ov = this._sell.put(k, v);
		return ov;
	}


	/**获取已销售数量*/
	public getSell(k: number) {
		return this._sell.get(k);
	}


	/**删除已销售数量*/
	public removeSell(k: number, autoDestroy = false): ShopSell {
		const ov = this._sell.remove(k);
		if (autoDestroy && ov) {
			ov.destroy();
		}
		return ov;
	}


	/**获取已销售数量映射表-键值(外部改变将导致出错，只能用于遍历)*/
	public getSellKeys(): number[] {
		return this._sell.getKeys();
	}


	/**获取已销售数量映射表-值(外部改变将导致出错，只能用于遍历)*/
	public getSellValues(): ShopSell[] {
		return this._sell.getValues();
	}


	/**清空已销售数量映射表*/
	public clearSellMap(autoDestroy = false): void {
		const ks = this._sell.getKeys();
		for (let i = ks.length - 1; i >= 0; i--) {
			this.removeSell(ks[i], autoDestroy);
		}
	}



	/**通过枚举获取值*/
	public getV(k: E_ShopManager): any {
		switch (k) {
			case E_ShopManager.SHOP: return this._shop;
			case E_ShopManager.SELL: return this._sell;
			default: return null;
		}
	}


	/**通过枚举设置值*/
	public setV(k: E_ShopManager, v: any): void {
		switch (k) {
			case E_ShopManager.SHOP: this._shop = v; break;
			case E_ShopManager.SELL: this._sell = v; break;
			default: break;
		}
	}


	/**初始化*/
	public resetProperty(fromDestroy = false): void {
		//各个商店
		if (this._shop) {
			const list = this._shop.getValues();
			for (let i = 0, len = list.length; i < len; i++) {
				list[i].destroy();
			}
			this._shop.clear();
		}
		else {
			this._shop = new HashMap<number, Shop>();
		}
		//已销售数量
		if (this._sell) {
			const list = this._sell.getValues();
			for (let i = 0, len = list.length; i < len; i++) {
				list[i].destroy();
			}
			this._sell.clear();
		}
		else {
			this._sell = new HashMap<number, ShopSell>();
		}
	}


	/**序列化*/
	public stringify(toString: boolean): string | any {
		const json: any = {};
		if (this._shop.size() > 0) {
			const ks = this._shop.getKeys();
			const vs = this._shop.getValues();
			const list: string[] = [];
			for (let i = 0, len = vs.length; i < len; i++) {
				list[i] = vs[i].stringify(false);
			}
			json.shop = [ks, list];
		}
		if (this._sell.size() > 0) {
			const ks = this._sell.getKeys();
			const vs = this._sell.getValues();
			const list: string[] = [];
			for (let i = 0, len = vs.length; i < len; i++) {
				list[i] = vs[i].stringify(false);
			}
			json.sell = [ks, list];
		}

		return toString ? JSON.stringify(json) : json;
	}


	/**反序列化*/
	public parse(jsonv: string | any): this {
		this.resetProperty();
		if (!jsonv) {
			return this;
		}
		const json = typeof (jsonv) === 'string' ? JSON.parse(jsonv) : jsonv;
		if (json.shop) {
			const ks: number[] = json.shop[0] || (json.shop.getKeys ? json.shop.getKeys() : null);	//对象可能是json或者结构体
			const vs: string[] = json.shop[1] || (json.shop.getValues ? json.shop.getValues() : null);
			if (ks && vs && ks.length === vs.length) {
				for (let i = 0, len = vs.length; i < len; i++) {
					this._shop.put(ks[i], Shop.create(vs[i]));
				}
			}
		}
		if (json.sell) {
			const ks: number[] = json.sell[0] || (json.sell.getKeys ? json.sell.getKeys() : null);	//对象可能是json或者结构体
			const vs: string[] = json.sell[1] || (json.sell.getValues ? json.sell.getValues() : null);
			if (ks && vs && ks.length === vs.length) {
				for (let i = 0, len = vs.length; i < len; i++) {
					this._sell.put(ks[i], ShopSell.create(vs[i]));
				}
			}
		}
		return this;
	}


	/**序列化-二进制*/
	public toBytes(byte: Byte): void {
		if (!byte) {
			return;
		}
		//各个商店
		{
			const ks = this._shop.getKeys();
			const vs = this._shop.getValues();
			const len = ks.length;
			byte.writeUint16(len);
			for (let i = 0; i < len; i++) {
				byte.writeUint32(ks[i]);
				vs[i].toBytes(byte);
			}
		}
		//已销售数量
		{
			const ks = this._sell.getKeys();
			const vs = this._sell.getValues();
			const len = ks.length;
			byte.writeUint16(len);
			for (let i = 0; i < len; i++) {
				byte.writeUint32(ks[i]);
				vs[i].toBytes(byte);
			}
		}
	}


	/**反序列化-二进制*/
	public fromBytes(byte: Byte): this {
		this.resetProperty();
		if (!byte) {
			return;
		}
		//各个商店
		{
			const len = byte.readUint16();
			for (let i = 0; i < len; i++) {
				const k = byte.readUint32();
				const v = Shop.create();
				v.fromBytes(byte);
				this._shop.put(k, v);
			}
		}
		//已销售数量
		{
			const len = byte.readUint16();
			for (let i = 0; i < len; i++) {
				const k = byte.readUint32();
				const v = ShopSell.create();
				v.fromBytes(byte);
				this._sell.put(k, v);
			}
		}
		return this;
	}


	/**克隆*/
	public clone(): ShopManager {
		const byte = Byte.createFromPool();
		this.toBytes(byte);
		byte.pos = 0;
		const clonev = ShopManager.create().fromBytes(byte);
		Byte.recoverToPool(byte);
		return clonev;
	}


	/**处理更新*/
	public processUpdate(jsonv: string): void {
		if (!jsonv) {
			return;
		}

		const eventID = ShopManager.EVENT_ID;
		const us = JSON.parse(jsonv);

		for (let i = 0, len = us.length; i < len;) {
			const idx = us[i];

			//各个商店
			if (idx === E_ShopManager.SHOP) {
				const k: number = us[i + 1];
				const ctrl: number = us[i + 2];
				if (ctrl === 0) {
					const oldv = this.removeShop(k);
					if (oldv) {
						oldv.destroy()
					}
				}
				else if (ctrl === 1) {
					const newv = Shop.create(us[i + 3]);
					const oldv = this.putShop(k, newv);
					if (oldv) {
						oldv.destroy()
					}
				}
				else {
					const curv = this.getShop(k);
					if (curv) {
						curv.processUpdate(us[i + 3]);
					}
					else {
						console.error('ShopManager Shop is not exist when update! k = ' + k);
					}
				}
				IAsync.dispatch(eventID, idx, k, ctrl);
				i += ctrl === 0 ? 3 : 4;
				continue;
			}

			//已销售数量
			if (idx === E_ShopManager.SELL) {
				const k: number = us[i + 1];
				const ctrl: number = us[i + 2];
				if (ctrl === 0) {
					const oldv = this.removeSell(k);
					if (oldv) {
						oldv.destroy()
					}
				}
				else if (ctrl === 1) {
					const newv = ShopSell.create(us[i + 3]);
					const oldv = this.putSell(k, newv);
					if (oldv) {
						oldv.destroy()
					}
				}
				else {
					const curv = this.getSell(k);
					if (curv) {
						curv.processUpdate(us[i + 3]);
					}
					else {
						console.error('ShopManager ShopSell is not exist when update! k = ' + k);
					}
				}
				IAsync.dispatch(eventID, idx, k, ctrl);
				i += ctrl === 0 ? 3 : 4;
				continue;
			}

			console.error('[Struct Data] can not find enum in ShopManager with idx = ' + idx + ', version maybe wrong.')
		}

		//全更事件
		ITimer.callLater(this, this.dispatchTotalUpdate);
	}


	/**比对不一致结果*/
	public getCompareInfo(other: ShopManager): string {
		if (!other) {
			return null;
		}

		const updates: any[] = [];


		//各个商店
		{
			const idx = E_ShopManager.SHOP;
			const ks1 = this._shop.getKeys();
			const ks2 = other._shop.getKeys();
			const rs = MathUtils.intersectSortedArray(ks1, ks2);
			if (rs[0].length > 0) {
				const list = rs[0];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getShop(k);
					const oldv = other.getShop(k);
					const ui = newv.getCompareInfo(oldv);
					if (ui && ui.length > 0) {
						updates.push(idx, k, 2, ui);
					}
				}
			}
			if (rs[1].length > 0) {
				const list = rs[1];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getShop(k);
					updates.push(idx, k, 1, newv.stringify(false));
				}
			}
			if (rs[2].length > 0) {
				const list = rs[2];
				for (let i = 0, len = list.length; i < len; i++) {
					updates.push(idx, list[i], 0);
				}
			}
		}

		//已销售数量
		{
			const idx = E_ShopManager.SELL;
			const ks1 = this._sell.getKeys();
			const ks2 = other._sell.getKeys();
			const rs = MathUtils.intersectSortedArray(ks1, ks2);
			if (rs[0].length > 0) {
				const list = rs[0];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getSell(k);
					const oldv = other.getSell(k);
					const ui = newv.getCompareInfo(oldv);
					if (ui && ui.length > 0) {
						updates.push(idx, k, 2, ui);
					}
				}
			}
			if (rs[1].length > 0) {
				const list = rs[1];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getSell(k);
					updates.push(idx, k, 1, newv.stringify(false));
				}
			}
			if (rs[2].length > 0) {
				const list = rs[2];
				for (let i = 0, len = list.length; i < len; i++) {
					updates.push(idx, list[i], 0);
				}
			}
		}

		const jsonv = updates.length === 0 ? null : JSON.stringify(updates);
		return jsonv;
	}


	/**全部更新*/
	protected dispatchTotalUpdate(): void {
		IAsync.dispatch(ShopManager.TOTAL_EVENT_ID, this.getV(0));
	}

}
